<template>
  <el-popover
    v-model:visible="visible"
    placement="bottom"
    trigger="click"
    :width="458"
    popper-class="bedno-edit-popover"
  >
    <template #reference>
      <slot name="reference">
        <el-button size="small" type="primary">设置床号</el-button>
      </slot>
    </template>

    <div class="bedno-edit-body">
      <div class="inputs-row">
        <div class="bed-input-item" v-for="(v, idx) in numbers" :key="idx">
          <el-input v-model="numbers[idx]" size="small" placeholder="" @input="onInput(idx)">
            <template #suffix>床</template>
          </el-input>
        </div>
      </div>
      <div class="hint-text">床号需为正整数，且在病区范围内不可重复</div>
      <div class="popover-footer">
        <el-button type="primary" size="small" @click="onConfirm">确定</el-button>
        <el-button size="small" @click="handleCancel">取消</el-button>
      </div>
    </div>
  </el-popover>
</template>

<script setup>
import { ref, watch, computed } from 'vue'
import { ElNotification } from 'element-plus'

const props = defineProps({
  modelValue: { type: Boolean, default: false },
  bedCount: { type: Number, required: true },
  initialSelected: { type: Array, default: () => [] },
  usedNumbers: { type: Array, default: () => [] }
})

const emit = defineEmits(['update:modelValue', 'confirm', 'cancel'])

const visible = ref(false)
const numbers = ref([]) // 纯数字数组

const usedSet = computed(() => new Set((props.usedNumbers || []).map(n => Number(n))))

watch(
  () => props.modelValue,
  val => {
    visible.value = val
    if (val) initNumbers()
  },
  { immediate: true }
)

watch(visible, v => {
  emit('update:modelValue', v)
  if (v) initNumbers()
})

const parseNum = val => {
  if (val == null) return null
  if (typeof val === 'number') return val
  const s = String(val).replace(/床$/, '')
  const n = parseInt(s, 10)
  return Number.isNaN(n) ? null : n
}

const initNumbers = () => {
  const count = Number(props.bedCount) || 0
  const init = Array.isArray(props.initialSelected) ? props.initialSelected.map(parseNum).filter(n => n != null) : []
  numbers.value = []
  if (init.length === count) {
    numbers.value = [...init]
    return
  }
  // 不匹配时，按唯一顺序生成
  const res = []
  const used = new Set(usedSet.value)
  let cur = 1
  while (used.has(cur)) cur++
  for (let i = 0; i < count; i++) {
    while (used.has(cur)) cur++
    res.push(cur)
    used.add(cur)
    cur++
  }
  numbers.value = res
}

const onInput = idx => {
  // 转为正整数（去除非数字）
  const raw = numbers.value[idx]
  const n = parseInt(String(raw).replace(/\D/g, ''), 10)
  numbers.value[idx] = Number.isNaN(n) ? '' : Math.max(1, n)
}

const onConfirm = () => {
  // 基本校验
  const arr = numbers.value.map(parseNum).filter(n => n != null)
  if (arr.length !== (Number(props.bedCount) || 0)) {
    ElNotification.warning('请完整填写所有床号')
    return
  }
  // 行内重复校验
  const localSet = new Set(arr)
  if (localSet.size !== arr.length) {
    ElNotification.warning('当前房间内床号存在重复')
    return
  }
  // 与其它房间重复校验
  for (const n of arr) {
    if (usedSet.value.has(n)) {
      ElNotification.warning(`床号 ${n} 与其他房间重复`)
      return
    }
  }
  emit('confirm', arr)
  visible.value = false
}

const handleCancel = () => {
  emit('cancel')
  visible.value = false
}
</script>

<style scoped>
.bedno-edit-body {
  padding: 4px 0 8px;
}
.inputs-row {
  display: flex;
  flex-wrap: wrap;
  gap: 16px;
}
.bed-input-item {
  width: 96px;
}
.hint-text {
  margin-top: 8px;
  color: #909399;
  font-size: 12px;
}
.popover-footer {
  margin-top: 12px;
  display: flex;
  justify-content: center;
  gap: 12px;
}
</style>
